package cn.buk.api.shdl.util;

import cn.buk.api.shdl.service.ShdlFlightServiceImpl;
import org.apache.http.Header;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User: yfdai
 */
public class HttpUtil extends BaseHttpClient {

    private static Logger logger = LogManager.getLogger(HttpUtil.class);

    public static String getUrl(String url, List<NameValuePair> params) {
        //TODO 判断params有的话，还要判断url的结果字符是否为"?"
        String uri = url;
        if (params != null) uri += URLEncodedUtils.format(params, "UTF-8");

        CloseableHttpClient httpClient = createHttpClient();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SO_TIMEOUT).setConnectTimeout(CONNECTION_TIMEOUT).build();

        HttpGet httpGet = new HttpGet(uri);
        httpGet.setConfig(requestConfig);
        String rs = "";

        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                rs = EntityUtils.toString(response.getEntity(), "UTF-8");
            } else {
                System.out.println(response.getStatusLine().toString());
            }

            response.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return rs;
    }

    public static String postUrl(String url, String body, Map<String, String> headers) {
        CloseableHttpClient httpClient = createHttpClient();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SO_TIMEOUT).setConnectTimeout(CONNECTION_TIMEOUT).build();

        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);

        String rs = "";

        try {
            if (body != null) {
                StringEntity entity = new StringEntity(body, "UTF-8");
                httpPost.setEntity(entity);
            }

            httpPost.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
            if (headers != null) {
                for (String key : headers.keySet()) {
                    httpPost.addHeader(key, headers.get(key));
                }
            }

            CloseableHttpResponse response = httpClient.execute(httpPost);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                rs = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            } else if (response != null) {
                System.out.println(url);
                System.out.println(response.getStatusLine());
                for (Header header : response.getAllHeaders()) {
                    System.out.println(header.getName() + " = " + header.getValue());
                }
            }

            response.close();
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        return rs;
    }

    public static Map<String, String> postUrlWithBasicAuth(final String url, String username, String password, String postStr) {
        CloseableHttpClient httpClient = createHttpClient();

        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SO_TIMEOUT).setConnectTimeout(CONNECTION_TIMEOUT).build();

        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);

        // 添加头部信息
        String authHeader = "Basic " + EncryptUtil.base64Encoding(username + ":" + password);
        // 将验证信息放入到 Header
        httpPost.addHeader(HttpHeaders.AUTHORIZATION, authHeader);

        httpPost.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");

        Map<String, String> map = new HashMap<>(2);

        String rs = "";

        try {
//            httpPost.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));
            StringEntity entity = new StringEntity(postStr, StandardCharsets.UTF_8);
            httpPost.setEntity(entity);

            CloseableHttpResponse response = httpClient.execute(httpPost);


            map.put("status", response.getStatusLine().getStatusCode() + "");
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                rs = EntityUtils.toString(response.getEntity(), "UTF-8");
                map.put("content", rs);
            } else if (response != null) {
                System.out.println(url);
                System.out.println(response.getStatusLine());
                for (Header header : response.getAllHeaders()) {
                    System.out.println(header.getName() + " = " + header.getValue());
                }

                if (response.getEntity() != null) {
                    rs = EntityUtils.toString(response.getEntity(), "UTF-8");
                    map.put("content", rs);
                }
            }

            response.close();
        } catch (HttpHostConnectException ex) {
            map.put("status", "1000");
            map.put("content", ex.getMessage());
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return map;
    }



    /**
     * 获取随机文件名
     * @return
     */
    public static String getRandomFileName() {
        return String.valueOf(System.currentTimeMillis());
    }


}
